use cmsis_rtos2_rs::static_mem::Mutex;
use periph_utils::GpioConfig;
use utils::BitSet;
use periph_utils::stm32f1;


#[derive(GpioConfig)]
#[gpio(init = "gpio_init",
    io(name = "pl", io = "PB3", mode = "OUT_PP", set, reset),
    io(name = "sck", io = "PB4", mode = "OUT_PP", set, reset),
    io(name = "q7", io = "PB5", mode = "IN_FLOAT", read),
    io(name = "loc2", io = "PB0", mode = "IN_FLOAT", read),
)]
struct Pin;

static MUTEX: Mutex = Mutex::uninit();


pub unsafe fn init() {
    MUTEX.init_once("mutex");
    Pin::gpio_init();
}

// 二次定位
#[inline(always)]
pub fn is_loc2_checked() -> bool {
    Pin::loc2_read()
}

// 旋转气缸 内
#[inline(always)]
pub fn is_cy_inner_checked() -> bool {
    !read().is_set(0)
}

// 旋转气缸 外
#[inline(always)]
pub fn is_cy_extern_checked() -> bool {
    !read().is_set(1)
}

// 气缸 上
#[inline(always)]
pub fn is_cy_top_checked() -> bool {
    !read().is_set(2)
}

// 气缸 下
#[inline(always)]
pub fn is_cy_bottom_checked() -> bool {
    !read().is_set(3)
}

#[inline(always)]
pub fn is_pick_motor_origin() -> bool {
    read().is_set(4)
}

#[inline(always)]
pub fn is_compr_checked() -> bool {
    !read().is_set(5)
}

#[inline(always)]
pub fn is_rotation_button_click() -> bool {
    !read().is_set(6)
}

#[inline(always)]
pub fn is_cargo_motor_origin() -> bool {
    read().is_set(7)
}

pub fn read() -> u8 {
    MUTEX.free(read_impl)
}


fn read_impl() -> u8 {
    let mut value = 0;
    Pin::pl_reset();
    Pin::pl_set();
    for _ in 0..8 {
        value <<= 1;
        if Pin::q7_read() {
            value |= 0x01;
        }
        Pin::sck_set();
        Pin::sck_reset();
    }
    value
}






